<template>
  <div class="transformer-control-container">
    <a-row :gutter="24">
      <!-- 左侧控制面板 -->
      <a-col :span="8">
        <a-card title="试验变控制面板" class="control-card">
          <template #extra><a @click="goToTestAdd">返回试验记录</a></template>
          <!-- 电压控制区域 -->
          <div class="control-section">
            <div class="section-header">
              <i class="fas fa-bolt control-icon"></i>
              <span class="section-title">电压控制</span>
            </div>

            <div class="voltage-display">
              <div class="voltage-value">{{ voltage }} kV</div>
              <div class="voltage-status" :class="voltageStatus">
                {{ voltageStatusText }}
              </div>
            </div>

            <div class="control-buttons">
              <a-button type="primary" size="large" class="control-btn rising-btn" :disabled="isOperating"
                @click="startRising">
                <i class="fas fa-arrow-up"></i> 升压
              </a-button>

              <a-button size="large" class="control-btn stop-btn" @click="stopOperation">
                <i class="fas fa-stop"></i> 停止
              </a-button>

              <a-button type="primary" size="large" class="control-btn falling-btn" :disabled="isOperating"
                @click="startFalling">
                <i class="fas fa-arrow-down"></i> 降压
              </a-button>
            </div>

            <div class="speed-control">
              <div class="control-label">调压速度</div>
              <a-slider v-model:value="voltageSpeed" :min="1" :max="10" :step="1" />
              <div class="speed-value">{{ voltageSpeed }} 档</div>
            </div>
          </div>

          <!-- 补偿控制区域 -->
          <div class="control-section">
            <div class="section-header">
              <i class="fas fa-sliders-h control-icon"></i>
              <span class="section-title">补偿控制</span>
            </div>

            <div class="compensation-control">
              <a-switch v-model:checked="compensationEnabled" />
              <span class="control-label">补偿允许</span>
            </div>

            <div class="compensation-control">
              <div class="control-label">补偿档位</div>
              <a-radio-group v-model:value="compensationLevel">
                <a-radio :value="1">1档</a-radio>
                <a-radio :value="2">2档</a-radio>
                <a-radio :value="3">3档</a-radio>
              </a-radio-group>
            </div>

            <div class="compensation-control">
              <div class="control-label">
                补偿值: {{ compensationValue }} kV
              </div>
              <a-slider v-model:value="compensationValue" :min="0" :max="50" :step="0.1" />
            </div>
          </div>

          <!-- 状态指示区域 -->
          <div class="control-section">
            <div class="section-header">
              <i class="fas fa-info-circle control-icon"></i>
              <span class="section-title">状态指示</span>
            </div>

            <div class="status-indicators">
              <div class="status-item">
                <div class="status-label">通讯状态</div>
                <div class="status-value" :class="{ 'status-ok': isConnected }">
                  {{ isConnected ? "正常" : "断开" }}
                </div>
              </div>

              <div class="status-item">
                <div class="status-label">运行状态</div>
                <div class="status-value" :class="{ 'status-running': isOperating }">
                  {{ isOperating ? "运行中" : "停止" }}
                </div>
              </div>

              <div class="status-item">
                <div class="status-label">电流值</div>
                <div class="status-value">{{ current }} A</div>
              </div>

              <div class="status-item">
                <div class="status-label">局放值</div>
                <div class="status-value">{{ partialDischarge }} pC</div>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>

      <!-- 右侧图表区域 -->
      <a-col :span="16">
        <a-card title="实时电压监测" class="chart-card">
          <div class="chart-container">
            <div ref="chartContainer" class="chart-wrapper"></div>
          </div>

          <div class="chart-controls">
            <a-button @click="clearChart">清空图表</a-button>
            <a-button @click="toggleAutoRefresh">
              {{ autoRefresh ? "停止刷新" : "开始刷新" }}
            </a-button>
          </div>
        </a-card>

        <!-- 实时数据表格 -->
        <a-card title="实时数据记录" class="data-card">
          <a-table :dataSource="voltageHistory" :columns="columns" :pagination="{ pageSize: 5 }" size="small" />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';

// 控制状态
const voltage = ref(0);
const voltageSpeed = ref(5);
const isOperating = ref(false);
const operationType = ref(''); // 'rising' 或 'falling'
const isConnected = ref(true);
const current = ref(0);
const partialDischarge = ref(0);

// 补偿控制
const compensationEnabled = ref(false);
const compensationLevel = ref(1);
const compensationValue = ref(0);

// 图表相关
const chartContainer = ref(null);
const chart = ref(null);
const autoRefresh = ref(true);

// 数据记录
const voltageHistory = ref([]);

// 表格列定义
const columns = [
  {
    title: "时间",
    dataIndex: "time",
    key: "time",
  },
  {
    title: "电压(kV)",
    dataIndex: "voltage",
    key: "voltage",
  },
  {
    title: "电流(A)",
    dataIndex: "current",
    key: "current",
  },
  {
    title: "局放(pC)",
    dataIndex: "partialDischarge",
    key: "partialDischarge",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
  },
];

const router = useRouter();
const goToTestAdd = () => {
  router.push('/add');
};

// 计算属性
const voltageStatus = computed(() => {
  if (voltage.value === 0) return "status-stopped";
  if (voltage.value < 100) return "status-low";
  if (voltage.value < 300) return "status-medium";
  return "status-high";
});

const voltageStatusText = computed(() => {
  if (voltage.value === 0) return "停止";
  if (voltage.value < 100) return "低电压";
  if (voltage.value < 300) return "中电压";
  return "高电压";
});

// 操作方法
const startRising = () => {
  if (isOperating.value) return;
  isOperating.value = true;
  operationType.value = "rising";
  operateVoltage();
};

const startFalling = () => {
  if (isOperating.value) return;
  isOperating.value = true;
  operationType.value = "falling";
  operateVoltage();
};

const stopOperation = () => {
  isOperating.value = false;
  operationType.value = "";
};

const operateVoltage = () => {
  if (!isOperating.value) return;

  const step = voltageSpeed.value * 0.5;

  if (operationType.value === "rising") {
    voltage.value = Math.min(500, voltage.value + step);
  } else if (operationType.value === "falling") {
    voltage.value = Math.max(0, voltage.value - step);
  }

  // 更新电流和局放值（模拟）
  updateMeasurements();

  // 添加到历史记录
  addToHistory();

  // 更新图表
  updateChart();

  // 继续操作
  if (isOperating.value) {
    setTimeout(operateVoltage, 200);
  }
};

const updateMeasurements = () => {
  // 模拟电流和局放值的变化
  current.value = (voltage.value * 0.8 + Math.random() * 10).toFixed(2);
  partialDischarge.value = (
    voltage.value * 0.3 +
    Math.random() * 5
  ).toFixed(2);
};

const addToHistory = () => {
  const now = new Date();
  const timeString = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;

  voltageHistory.value.unshift({
    key: Date.now(),
    time: timeString,
    voltage: voltage.value.toFixed(2),
    current: current.value,
    partialDischarge: partialDischarge.value,
    status: isOperating.value
      ? operationType.value === "rising"
        ? "升压"
        : "降压"
      : "停止",
  });

  // 限制历史记录数量
  if (voltageHistory.value.length > 50) {
    voltageHistory.value.pop();
  }
};

// 图表相关方法
const initChart = () => {
  if (!chartContainer.value) return;

  chart.value = echarts.init(chartContainer.value);

  const option = {
    title: {
      text: "实时电压变化曲线",
    },
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: [],
    },
    yAxis: {
      type: "value",
      name: "电压(kV)",
    },
    series: [
      {
        data: [],
        type: "line",
        smooth: true,
        symbol: "none",
        lineStyle: {
          color: "#1890ff",
          width: 2,
        },
        areaStyle: {
          color: "rgba(24, 144, 255, 0.1)",
        },
      },
    ],
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
  };

  chart.value.setOption(option);
};

const updateChart = () => {
  if (!chart.value) return;

  const now = new Date();
  const timeString = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;

  const option = {
    xAxis: {
      data: (chart.value.getOption().xAxis[0].data || []).concat(
        timeString
      ),
    },
    series: [
      {
        data: (chart.value.getOption().series[0].data || []).concat(
          voltage.value
        ),
      },
    ],
  };

  // 限制显示的数据点数量
  if (option.xAxis.data.length > 20) {
    option.xAxis.data.shift();
    option.series[0].data.shift();
  }

  chart.value.setOption(option);
};

const clearChart = () => {
  if (!chart.value) return;

  chart.value.setOption({
    xAxis: {
      data: [],
    },
    series: [
      {
        data: [],
      },
    ],
  });
};

const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value;
};

// 生命周期
onMounted(() => {
  initChart();

  // 监听窗口大小变化
  window.addEventListener("resize", () => {
    if (chart.value) {
      chart.value.resize();
    }
  });
});

onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.dispose();
  }
});
</script>

<style scoped>
.transformer-control-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.control-card,
.chart-card,
.data-card {
  margin-bottom: 24px;
}

.control-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.control-icon {
  margin-right: 8px;
  color: #1890ff;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
}

.voltage-display {
  text-align: center;
  margin-bottom: 20px;
}

.voltage-value {
  font-size: 32px;
  font-weight: 700;
  color: #1890ff;
  margin-bottom: 8px;
}

.voltage-status {
  font-size: 14px;
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 12px;
  display: inline-block;
}

.voltage-status.status-stopped {
  background-color: #f0f0f0;
  color: #666;
}

.voltage-status.status-low {
  background-color: #e6f7ff;
  color: #1890ff;
}

.voltage-status.status-medium {
  background-color: #fffbe6;
  color: #faad14;
}

.voltage-status.status-high {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.control-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.control-btn {
  flex: 1;
  margin: 0 8px;
}

.rising-btn {
  background-color: #52c41a !important;
  border-color: #52c41a !important;
}

.falling-btn {
  background-color: #ff4d4f !important;
  border-color: #ff4d4f !important;
}

.stop-btn {
  background-color: #faad14 !important;
  border-color: #faad14 !important;
  color: white !important;
}

.speed-control {
  text-align: center;
}

.control-label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #1d2129;
}

.speed-value {
  margin-top: 8px;
  font-weight: 500;
  color: #1890ff;
}

.compensation-control {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.compensation-control .control-label {
  margin: 0 12px 0 8px;
}

.status-indicators {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.status-item {
  display: flex;
  flex-direction: column;
  padding: 8px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.status-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.status-value {
  font-size: 14px;
  font-weight: 500;
}

.status-value.status-ok {
  color: #52c41a;
}

.status-value.status-running {
  color: #1890ff;
}

.chart-container {
  height: 400px;
  margin-bottom: 16px;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
}

.chart-controls {
  text-align: center;
}

.chart-controls button {
  margin: 0 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .transformer-control-container {
    padding: 12px;
  }

  .control-buttons {
    flex-direction: column;
  }

  .control-btn {
    margin: 4px 0;
  }

  .status-indicators {
    grid-template-columns: 1fr;
  }

  .chart-container {
    height: 300px;
  }
}
</style>